import 'package:flutter/material.dart';
import 'package:flutter_module/tabbar/shop/deviceModel.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'shopModel.dart';
import 'package:flutter_module/tool/shopDeviceManager.dart';
import 'package:provider/provider.dart';
import 'shopScreenProvider.dart';
import 'shop_section_widget.dart';
import 'shop_row_widget.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

// 这个页面用StatefulWidget的原因是嵌入DefaultTabController的页面要保持状态
// 用StatelessWidget则不行,及时用了provider状态管理也无效,原因未知
class ShopScreenAll extends StatefulWidget {
  @override
  _ShopScreenAllState createState() => _ShopScreenAllState();
}

// with AutomaticKeepAliveClientMixin 为了保持状态
class _ShopScreenAllState extends State<ShopScreenAll> with AutomaticKeepAliveClientMixin {

  // 必须重写
  @override
  bool get wantKeepAlive => true;

  EasyRefreshController _controller;
  bool _isRefresh = false;
  
  @override
  void initState() { 
    super.initState();
    _controller = EasyRefreshController();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return  FutureBuilder(
    future: ShopDeviceManager.fetchAllSortShopsDevice(),
    builder: (context,snapshot){

      if (!snapshot.hasData) {
        return Center(
          child: SpinKitCircle(color: Colors.lightBlue,),
        );
      }

      return Consumer<ShopScreenProvider>(
        builder: (context,provider,child){
          
          if (!_isRefresh) {
            provider.setShops(snapshot.data);
          }else{
            _isRefresh = false;
          }
          
          List<ShopSortModel> list = provider.list;

          if (list.length == 0) {
            return Container(child: Center(child: Text('未搜索到门店')));
          }
          
          return EasyRefresh(
            // 开启控制结束刷新
            enableControlFinishRefresh: true,
            controller: _controller,
            child: ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: list.length,
              itemBuilder: (context,section){
                return Column(
                  children: <Widget>[
                    Container(
                      height: 30,
                      color: Color.fromRGBO(235, 239, 244, 1),
                      child: sectionTableViewSectionWidget(list[section]),
                    ),
                    ListView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemCount: list[section].shops.length,
                      itemBuilder: (context,row){
                        return sectionTableViewRowWidget(list[section].shops[row],provider);
                      },
                    )
                  ],
                );
              },
            ),
            onRefresh: () async {
              ShopDeviceManager.fetchAllSortShopsDevice().then((val){
                _isRefresh = true;
                provider.refreshShops(val);
                _controller.finishRefresh();
              });
            },
          );
        }
      );
    },
  );
  }
}

Widget sectionTableViewSectionWidget(ShopSortModel sortModel) {

  return ShopSectionWidget(sortModel.initial);
}

Widget sectionTableViewRowWidget(ShopModel model,ShopScreenProvider provider) {
  return ShopRowWidget(
    model:model,
    collectionOnTap: (){

      if (model.isCollection == false) {
        ShopDeviceManager.additionCollectionShop(model.uuid).then((value){
          provider.collectionStautsChange(model.uuid);
          Fluttertoast.showToast(
            msg: '收藏成功',
            gravity: ToastGravity.CENTER
          );
        }).catchError((error){
          Fluttertoast.showToast(
            msg: '收藏失败',
            gravity: ToastGravity.CENTER
          );
        });
      }else{
        ShopDeviceManager.deleteCollectionShop(model.uuid).then((value){
          provider.collectionStautsChange(model.uuid);
          Fluttertoast.showToast(
            msg: '取消收藏成功',
            gravity: ToastGravity.CENTER
          );
        }).catchError((error){
          Fluttertoast.showToast(
            msg: '取消收藏失败',
            gravity: ToastGravity.CENTER
          );
        });
      }
    },
  );
}